import classNames from "classnames"
import React, { createContext, useState } from "react"
import { MenuItemProps } from "./menuItem"

export interface MenuProps {
    defaultIndex?: string
    // activeIndex?: number
    mode?:MenuMode
    className?: string
    style?:React.CSSProperties
    onSelect?:SelectCallback
    children?:React.ReactNode,
    defaultOpenSubMenus?:string[] // 默认 展开的二级菜单
}

interface IMenuContext {
    index: string,
    onSelect?: SelectCallback,
    mode?:MenuMode,
    defaultOpenSubMenus?:string[]
}


type MenuMode = 'horizontal' | 'vertical'
type SelectCallback = (selectedIndex: string) => void

// 创建上下文
export const MenuContext = createContext<IMenuContext>({ index:'0' })

const Menu = ({
    defaultIndex = "0",
    mode = 'horizontal',
    style,
    className,
    children,
    onSelect,
    defaultOpenSubMenus=[]
}:MenuProps) => {
    const classes = classNames('leo-menu',className,{
        'menu-vertical': mode === 'vertical',
        'menu-horizontal': mode !== 'vertical',
    })
    const [currentActive, setActive] = useState<string>(defaultIndex)
    const handleClick = (index:string) => {
        setActive(index)
        if(onSelect) {
            onSelect(index)
          }
    }
    const passedContext:IMenuContext = {
        index:currentActive,
        // 子组件触发点击事件
        onSelect: handleClick,
        mode,
        defaultOpenSubMenus
    }
    const renderChildren = () => {
        return React.Children.map(children, (child, index) => {
            const childElement = child as React.FunctionComponentElement<MenuItemProps>
            const { displayName } = childElement.type
            if (displayName === 'MenuItem' || displayName === 'SubMenu') {
                return React.cloneElement(childElement, {
                    index: index.toString()
                })
            } else {
                console.error("Warning: Menu has a child which is not a MenuItem component")
            }
        })
    }
    return (
        <ul className={classes} style={style} data-testid='test-menu'>
            <MenuContext.Provider value={passedContext}>
                { renderChildren() }
            </MenuContext.Provider>
        </ul>
    )
}

export default Menu